//
//  ZDBExchangeDetailViewController.m
//  ZDB
//
//  Created by 微笑吧阳光 on 2020/3/19.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBExchangeDetailViewController.h"
#import "ExchangeDetailHeaderView.h"
#import "ZDBTextStyleTableViewCell.h"
#import "ZDBAddreassViewController.h"
#import "ZDBExchangeOrderViewController.h"

@interface ZDBExchangeDetailViewController ()
<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic,strong) ExchangeDetailHeaderView * tableviewHeadView;
@property (nonatomic,strong) UIButton * bottomBtn;
@property (nonatomic, strong) NSDictionary * adressDicc;


@end

@implementation ZDBExchangeDetailViewController
-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
   
    self.tableviewHeadView.frame = CGRectMake(0, 0, UIScreenWidth, kScreenWidth *0.59+120);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     self.adressDicc = [NSDictionary dictionary];
    [self.view addSubview:self.tableView];
    [self getAdressList];
    self.tableviewHeadView =[[NSBundle mainBundle] loadNibNamed:@"ExchangeDetailHeaderView" owner:self options:nil].lastObject;
    self.tableviewHeadView.frame = CGRectMake(0, 0, UIScreenWidth, kScreenWidth *0.59+120);
    self.tableviewHeadView.modell = self.modell;
    self.tableView.tableHeaderView = self.tableviewHeadView;
    [self.tableView reloadData];
    self.bottomBtn = [BBControl createButtonWithFrame:CGRectMake(30, kScreenHeight-15-50-kStatusBarAndNavigationBarHeight, kScreenWidth-60, 50) target:self SEL:@selector(bottomBtnClick:) title:@""];
    [self.bottomBtn setImage:[UIImage imageNamed:@"Exchange_duihuanbtn"] forState:0];
    [self.view addSubview:self.bottomBtn];


}
-(void)bottomBtnClick:(UIButton *)sender{
    
    
    if (![DJLoginHelper sharedInstance].is_Login) {
         [[DJLoginHelper sharedInstance] dj_showLoginVC:self];
         return;
     }
    
    NSMutableDictionary * dataDicc = [self.modell toDictionary].mutableCopy;
    if (!kDictIsEmpty(self.adressDicc)) {
        [dataDicc setValue:self.adressDicc forKey:@"addressInfo"];
    }
    WEAKSELF
    [[ZDBAlertHelper sharedInstance] alert_PopExchangeInfoWith:dataDicc andActionBlock:^(NSInteger actionType, NSDictionary * _Nonnull resultDicc) {
        STRONGSELFFor(weakSelf);
        if (actionType ==200) {
          //  __block ViewController/*主控制器*/ *weakSelf = self;
            NSDictionary * adsDicc = [resultDicc jsonDict:@"addressInfo"];

                  NSMutableDictionary * infoDicc = [NSMutableDictionary dictionary];
                  [infoDicc setValue:@([resultDicc jsonInteger:@"id"]) forKey:@"igid"];
                  [infoDicc setValue:@([adsDicc jsonInteger:@"id"]) forKey:@"uaid"];
                  [strongSelf exchangeGoodsRequest:infoDicc];
         
        
        }else if (actionType==300){
            
            ZDBAddreassViewController * adsVC = [ZDBAddreassViewController new];
            adsVC.title = @"我的地址";
            adsVC.is_SingleSeclect = YES;
            adsVC.AddreassSeclectBlock = ^(NSDictionary * _Nonnull dataDicc) {
                [strongSelf showPopSureWithAddressDicc:dataDicc];
            };
            [strongSelf.navigationController pushViewController:adsVC animated:YES];
        }
    }];
    
}
-(void)getAdressList{
  //userAddress_getList
    NSString  * inurl = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"userAddress_getList"];
       WEAKSELF
       [[SmileHttpTool sharedInstance] POST :inurl parameters:nil origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
         STRONGSELFFor(weakSelf)
           
           if (statusCode==0) {
           NSLog(@"integralGoods_GetList----%@",responseObject);
               NSArray * dataArry = [NSArray arrayWithArray:responseObject];
               if (dataArry.count>0) {
                   strongSelf.adressDicc = [dataArry firstObject];
               }
           }else{
                [JMNotifyView showNotify:message isSuccessful:NO];
           }
             
           // [strongSelf stopLoadingAnimation];
           [strongSelf.tableView reloadData];
           [strongSelf.tableView.mj_header endRefreshing];
       } failure:^(id responseObject, NSError *error) {
           NSLog(@"error----%@",error);
            STRONGSELFFor(weakSelf)
             [strongSelf.tableView.mj_header endRefreshing];
           [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
           // [self stopLoadingAnimation];
       }];

}
-(void)showPopSureWithAddressDicc:(NSDictionary *)addressDicc{
    
     NSMutableDictionary * dataDicc = [self.modell toDictionary].mutableCopy;
     [dataDicc setValue:addressDicc forKey:@"addressInfo"];
    WEAKSELF
    [[ZDBAlertHelper sharedInstance] alert_PopExchangeInfoWith:dataDicc andActionBlock:^(NSInteger actionType, NSDictionary * _Nonnull resultDicc) {
        STRONGSELFFor(weakSelf);
        if (actionType ==200) {
       
            NSLog(@"可以请求了");
            
            NSDictionary * adsDicc = [resultDicc jsonDict:@"addressInfo"];

            NSMutableDictionary * infoDicc = [NSMutableDictionary dictionary];
            [infoDicc setValue:@([resultDicc jsonInteger:@"id"]) forKey:@"igid"];
            [infoDicc setValue:@([adsDicc jsonInteger:@"id"]) forKey:@"uaid"];
            [strongSelf exchangeGoodsRequest:infoDicc];
            
        }else if (actionType==300){
            
            ZDBAddreassViewController * adsVC = [ZDBAddreassViewController new];
            adsVC.title = @"我的地址";
            adsVC.is_SingleSeclect = YES;
            adsVC.AddreassSeclectBlock = ^(NSDictionary * _Nonnull dataDicc) {
                [strongSelf showPopSureWithAddressDicc:dataDicc];
            };
            [strongSelf.navigationController pushViewController:adsVC animated:YES];
        }
    }];
    
}

-(void)exchangeGoodsRequest:(NSMutableDictionary *)dataDicc{
    
    if (kStringIsEmpty([dataDicc jsonString:@"uaid"])) {
        [JMNotifyView showNotify:@"请添加收货地址" isSuccessful:NO];
        return;
    }

    NSString  * inurl = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"userGoods_exchangeGoodst"];
    WEAKSELF
        [[SmileHttpTool sharedInstance] POST :inurl parameters:dataDicc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
          STRONGSELFFor(weakSelf)
            
            if (statusCode==0) {
           // NSLog(@"userGoods_exchangeGoodst----%@",responseObject);
               //
                    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0/*延迟执行时间*/ * NSEC_PER_SEC));
                
                    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                        [strongSelf showSuccessPopView];
                    });
            }else{
                 [JMNotifyView showNotify:message isSuccessful:NO];
            }
            // [strongSelf stopLoadingAnimation];
            
        } failure:^(id responseObject, NSError *error) {
            NSLog(@"error----%@",error);
            // STRONGSELFFor(weakSelf)
             
            [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
            // [self stopLoadingAnimation];
        }];

    
}

-(void)showSuccessPopView{

    WEAKSELF
    [[ZDBAlertHelper sharedInstance] alert_PopExchangeReslutsWithActionBlock:^(NSInteger actionType) {
       STRONGSELFFor(weakSelf);
        if (actionType ==201) {
            [strongSelf.navigationController popViewControllerAnimated:YES];
        }else{
            
            ZDBExchangeOrderViewController * orderVC = [ZDBExchangeOrderViewController new];
            orderVC.title = @"兑换订单";
            [strongSelf.navigationController pushViewController:orderVC animated:YES];
            
        }
        
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ZDBTextStyleTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"ZDBTextStyleTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray * titleArry = @[@"商品参数",@"兑换说明"];
    cell.titleLab.text = titleArry[indexPath.row];
    if (indexPath.row==0) {
        cell.contentLab.text = self.modell.content;
    }else
    {
        NSString * str = @"1.用户通过消耗积分兑换商品；\n2.兑换的商品不得高于目前用户已有积分；\n3.兑换的商品图片仅供参考，系统发货商品主要根据商品价格发放；\n4.后台发放商品之后，会提供物流信息（物流公司以及物流单号），用户可在个人中心兑换订单查看\n5.后台检测用户若采用非法手段兑换商品，则永久封停账号。\n※掌兑宝在法律允许范围内保留对本活动的最终解释权。";
         cell.contentLab.attributedText =[ZBDUnit finderattributedLinesString:str attributedString:str color:ColorStr(@"666666") font:AutoFont(13)] ;
    }
    // KViewRadius(cell.infoView, 5);
    return cell;
  
}


#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight-kStatusBarAndNavigationBarHeight-TABBAR_HEIGHT)style:UITableViewStyleGrouped];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.estimatedRowHeight = 100;
        _tableView.backgroundColor =  RGBA(249, 249, 249, 1);
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"ZDBTextStyleTableViewCell" bundle:nil]  forCellReuseIdentifier:@"ZDBTextStyleTableViewCell"];
        //_tableView.tableHeaderView =self.tableviewHeadView;
    }
    return _tableView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
